package com.apes.hr.salary.rewardPunish.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.salary.rewardPunish.model.RewardPunishType;
import com.apes.hr.salary.rewardPunish.repository.RewardPunishTypeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.model.EnumerationType;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationTypeRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.repository.LocalPermitItemRepository;
import com.apes.scm.rbac.repository.PostRepository;
import com.apes.scm.rbac.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能：奖惩类型服务
 *
 * @author HuJianlin
 * @create 2018-01-30 11:35
 */
@Service("rewardPunishTypeService")
public class RewardPunishTypeService extends DomainService {

    @Autowired
    RewardPunishTypeRepository rewardPunishTypeRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    EnumerationTypeRepository enumerationTypeRepository;

    @Autowired
    PostRepository postRepository;
    @Autowired
    LocalPermitItemRepository localPermitItemRepository ;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    /**
     * 功能：创建奖惩类型
     *
     * @param request
     * @return
     */
    public RewardPunishType save(SimpleRequest request) {
        RewardPunishType ptType = request.getO(RewardPunishType.class);
        int limitValueL = ptType.getLimitValueL();
        int limitValueU =ptType.getLimitValueU();
        double limitAmtL = ptType.getLimitAmtL();
        double limitAmtU = ptType.getLimitAmtU();
        if(limitAmtL>limitAmtU) throw new RuntimeException("奖罚金额下限必须小于奖罚金额上限!");
        if(limitValueL>limitValueU) throw new RuntimeException("奖罚分值下限必须小于奖罚分值上限!");
        Post post = postRepository.findOne(request.getPostId());
        ptType.setCompany(post.getCompany());
        ptType.setDept(post.getDept());
        ptType.setState("create");
        return rewardPunishTypeRepository.saveAndFlush(ptType);
    }

    /**
     * 检查数据判断，判读当前的输入版本信息
     * @param request
     */
    public RewardPunishType checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        RewardPunishType oldRewardPunishType = rewardPunishTypeRepository.findOne(id);
        if (oldRewardPunishType == null) throw new RuntimeException("奖惩类型【" + id + "】在系统中不存在。");
        if (oldRewardPunishType.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        RewardPunishType ptType = request.getO(RewardPunishType.class);
        int limitValueL = ptType.getLimitValueL();
        int limitValueU =ptType.getLimitValueU();
        double limitAmtL = ptType.getLimitAmtL();
        double limitAmtU = ptType.getLimitAmtU();
        if(limitAmtL>limitAmtU) throw new RuntimeException("奖罚金额下限必须小于奖罚金额上限!");
        if(limitValueL>limitValueU) throw new RuntimeException("奖罚分值下限必须小于奖罚分值上限!");
        return ptType;
    }

    public RewardPunishType update(SimpleRequest request){
        // 检查数据
        RewardPunishType oill = checkData(request);
        RewardPunishType ptType = request.getO(RewardPunishType.class);
        return rewardPunishTypeRepository.saveAndFlush(ptType);
    }

    /**
     * 功能：审核奖惩记录
     *
     * @param request
     * @return
     */
    public RewardPunishType approve(SimpleRequest request) {
        RewardPunishType oldBill = checkData(request);
        if (oldBill.getApproveDate() != null) throw new RuntimeException("奖惩类型：" + request.get("id") + " 在系统中已审核。");
        RewardPunishType ptType = request.getO(RewardPunishType.class);
        ptType.setState("approve");
        ptType.setApproveDate(new Date());
        ptType.setApproveUid(this.getPerson(request));
        return rewardPunishTypeRepository.saveAndFlush(ptType);
    }


    /**
     * 删除奖惩类型
     * @param request
     * @return
     */
    public RewardPunishType delete(SimpleRequest request) {
        // 检查数据
        checkData(request);

        String id = request.get("id");
        RewardPunishType ptType = rewardPunishTypeRepository.findOne(id);
        ptType.setState("delete");

        return rewardPunishTypeRepository.saveAndFlush(ptType);
    }
    
    public RewardPunishType findOne(SimpleRequest request) throws Exception {
        String id = request.get("id");
        return rewardPunishTypeRepository.findOne(id);
    }

    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<RewardPunishType> find(SimpleRequest request) {
        String value = request.get("key");
        List<String> orgIds = SpringManager.getBean(PostService.class).findLocalPermitItems(request.getPostId(), "pp_search", "pt_company");
        List<PartyRole> roleList = new ArrayList<>();
        if(orgIds.isEmpty()){
            roleList.addAll(partyRoleRepository.findAllCompany());
        }
        orgIds.forEach(s -> {
            roleList.add(partyRoleRepository.findOne(s));
        });
        return rewardPunishTypeRepository.find(value, value,roleList, PageRequest.of(request.get("page"), request.get("size")) );
    }

    /**
     *  查询奖惩类别
     */
    public Page<Enumeration> findCategory(SimpleRequest request) {
        String sKey= request.get("key");
        EnumerationType enumerationType = enumerationTypeRepository.findOne("rewardPunishCategory");
        String sEnumerationType = enumerationType.getId();
        if(sKey!=null||sKey !=""){
            return enumerationRepository.findByTypeAndKey(sKey,sEnumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }else {
            return enumerationRepository.findByType(enumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }
    }

    /**
     *  查询指标类别
     */
    public Page<Enumeration> findQuotaType(SimpleRequest request) {
        String sKey= request.get("key");
        EnumerationType enumerationType = enumerationTypeRepository.findOne("rewardPunishQuotaType");
        String sEnumerationType = enumerationType.getId();
        if(sKey!=null||sKey !=""){
            return enumerationRepository.findByTypeAndKey(sKey,sEnumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }else {
            return enumerationRepository.findByType(enumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }
    }

}
